﻿using jvncorelib.EncryptorLib;
using Microsoft.AspNetCore.DataProtection;
using System;
using System.Security.Cryptography;

namespace EOM.TSHotelManagement.Common.Util
{
    public class DataProtectionHelper
    {
        private readonly EncryptLib _encryptLib;
        private readonly IDataProtector _employeeProtector;
        private readonly IDataProtector _reservationProtector;
        private readonly IDataProtector _customerProtector;
        private readonly IDataProtector _adminProtector;

        public DataProtectionHelper(EncryptLib encryptLib, IDataProtectionProvider dataProtectionProvider)
        {
            _encryptLib = encryptLib ?? throw new ArgumentNullException(nameof(encryptLib));
            _employeeProtector = dataProtectionProvider.CreateProtector("EmployeeInfoProtector");
            _reservationProtector = dataProtectionProvider.CreateProtector("ReservationInfoProtector");
            _customerProtector = dataProtectionProvider.CreateProtector("CustomerInfoProtector");
            _adminProtector = dataProtectionProvider.CreateProtector("AdminInfoProtector");
        }

        private string DecryptData(string encryptedData, IDataProtector protector)
        {
            if (string.IsNullOrEmpty(encryptedData))
                return encryptedData;

            try
            {
                return protector.Unprotect(encryptedData);
            }
            catch (CryptographicException)
            {
                try
                {
                    return _encryptLib.Decryption(encryptedData);
                }
                catch
                {
                    return encryptedData;
                }
            }
        }

        private string EncryptData(string plainText, IDataProtector protector)
        {
            return string.IsNullOrEmpty(plainText)
                ? plainText
                : protector.Protect(plainText);
        }

        public string DecryptEmployeeData(string encryptedData)
            => DecryptData(encryptedData, _employeeProtector);

        public string EncryptEmployeeData(string plainText)
            => EncryptData(plainText, _employeeProtector);

        public string DecryptReserData(string encryptedData)
            => DecryptData(encryptedData, _reservationProtector);

        public string EncryptReserData(string plainText)
            => EncryptData(plainText, _reservationProtector);

        public string DecryptCustomerData(string encryptedData)
            => DecryptData(encryptedData, _customerProtector);

        public string EncryptCustomerData(string plainText)
            => EncryptData(plainText, _customerProtector);

        public string DecryptAdministratorData(string encryptedData)
            => DecryptData(encryptedData, _adminProtector);

        public string EncryptAdministratorData(string plainText)
            => EncryptData(plainText, _adminProtector);
    }
}